// ************************************
// CORE FUNCTION
// ************************************
var highlightChanges = "on";

// mock window.open() to prevent popups
injectScript("window.open = function(){};");

chrome.extension.sendRequest({
	"fieldId": "extensionStatus"
}, function(response) {
	if (response.fieldValue != "off") {
		chrome.extension.sendRequest({
			"fieldId": "highlightChanges"
		}, function(response) {
			if (response.fieldValue == "off") {
				highlightChanges = "off";
			}
			start();
		});
	}
});


function start() {


	// ************************************
	// HOSTELS PAGE
	// ************************************
	if (isURL("http://www.ryanairhotels.com/")) {
		window.close();
		console.log("closing... HOSTELS");
	}


	// ************************************
	// ITINERARY PAGE
	// ************************************
	runIfExists("#container div#status", function() {
		if (document.title === "Itinerary - Ryanair.com") {
			console.log("Itinerary page");
			$("#container").css("z-index", "9999999999999");
			$(".gapBottom, #cpbuttons").remove();
			$("#container #content #main > div").remove();
			$('body > div:not(#container)').remove();
			runIfExists("body > div:not(#container)", function() {
				$('body > div:not(#container)').remove();
			});
		}
	});


	// ************************************
	// EXTRASERVICES BOOKING PAGE https://www.bookryanair.com/SkySales/booking.aspx?culture=en-gb&lc=en-gb#ExtraServices
	// ************************************
	runIfExists("#GrpExtraServices_ButtonSubmit", function() {
		if (document.title === "ExtraServices - Ryanair.com") {
			console.log("EXTRASERVICES page");
			$("#GrpExtraServices_ParkingInputGrpExtraServices_DisableParking").click();
			$("#GrpExtraServices_SamsoniteInputGroupGrpExtraServices_SamsoniteInputGrpExtraServicesSamInp_rbNoBagType").click();
			$("*[name='GrpExtraServices$RyanairTalkServices$RTOptions']").val("ZZ");
			$("#transfer-1").val('XX');
			$("#RTOptions").val('ZZ');
			$("#activCITYNONE").click();		
			executeIfConfigured("skipServicesChange", "on", function() {
				$("#GrpExtraServices_ButtonSubmit").click();
			});
		}
	});

	// ************************************
	// EXTRASERVICES WEB-CHECKIN https://www.bookryanair.com/SkySales/Booking.aspx?culture=en-ie&lc=en-ie#ExtraServicesChangeWCI
	// ************************************
	runIfExists("#formaction[value='ExtraServicesChangeWCI.aspx']", function() {
		console.log("EXTRASERVICES WEB-CHECKIN page");
		$("#GrpExtraServices_GrpExtraServicesParkingInput_DisableParking").click();
		$("#GrpExtraServices_GrpExtraServicesSamsoniteInputGroup_SamsoniteInputGrpExtraServicesSamInp_rbNoBagType").click();
		$("#transfer_1").val('XX');
		$("#RTOptions").val('ZZ');
		executeIfConfigured("skipServicesChange", "on", function() {
			$("input[name='GrpExtraServicesChange$ButtonSkip']").click();
		});
	});

	// ************************************
	// MAIN PAGE
	// ************************************
	runIfExists("div#ryanairBookingForm #termsAccept", function() {
		clickOnElement("div#ryanairBookingForm #termsAccept");
		$("iframe, #bookHotelForm").remove();
		console.log("Main page");
	});

	// ************************************
	// SERVICES PAGE
	// ************************************
	runIfExists("#GrpServices_AgreementServices_Agreement", function() {
		console.log("Services page");
		$("#GrpServices_AgreementServices_Agreement").click();
		$("#pb_rd_0_PB_0").click();
		setValueToField("GrpServices_InsuranceServices_InsuranceSelect_ResidencyCountry_0");
		setValueToField("firstname");
		setValueToField("lastname");
		setValueToField("title");
		setValueToField("bags_0_0");
		$("#smsNoConfirmation").click();
		$("#GrpServices_GrpServiesSamsoniteInputGroup_SamsoniteInputGrpServicesSamInp_rbNoBagType").click();
		$('#GrpServices_ButtonSubmit').removeAttr("onClick");
		$('#GrpServices_ButtonSubmit').unbind("onclick");
	});

	runIfExists("#InsPopup #btnNo:visible", function() {
		injectScript('$("#btnNo").click();');
	});


	// ************************************
	// Car Hire PAGE https://www.bookryanair.com/SkySales/booking.aspx?culture=en-gb&lc=en-gb#CarHire
	// ************************************
	runIfExists("#CarHireControl_ButtonSubmit", function() {
		console.log("Car Hire page");
		clickOnElement("#CarHireControl_ButtonSubmit");
	});

	// ************************************
	// Payment PAGE
	// ************************************
	runIfExists("#PaymentInputPaymentView_Addr1:visible", function() {
		console.log("Payment page");
		runIfDisapear("#loading:visible", function() {
			console.log("Payment page loading dissapeard");
			$("#PaymentInputPaymentView_Method").change();
			$("#PaymentInputPaymentView_Method").change();
			$("#PaymentInputPaymentView_Method").change();
			$("#PaymentInputPaymentView_Method").change();
			setValueToField('PaymentInputPaymentView_Email,#EmailConfirm');
			setValueToField('PaymentInputPaymentView_Country');
			setValueToField('PaymentInputPaymentView_FirstName');
			setValueToField('PaymentInputPaymentView_LastName');
			setValueToField('PaymentInputPaymentView_Title');
			setValueToField('PaymentInputPaymentView_ACCTNO');
			setValueToField('PaymentInputPaymentView_Addr1');
			setValueToField('PaymentInputPaymentView_Addr2');
			setValueToField('PaymentInputPaymentView_Addr3');
			setValueToField('PaymentInputPaymentView_City');
			setValueToField('PaymentInputPaymentView_PostCode');
			//TODO: fix dropdown with credit card types
			//setValueToField('PaymentInputPaymentView_Method');
			setValueToField('PhoneCountry');
			setValueToField('AreaCode');
			setValueToField('PhoneNumber');
			$("#ptwNo").click();
			$("#rightoutside").remove();
			$($("#main > div")[1]).remove();
		});
	});


	// ************************************
	// Web checkin PAGE 1
	// ************************************
	runIfExists("#BookingRetrieveSecurity_CARDNUMBER1", function() {
		console.log("Web Checkin page 1");
		$("#radioButtonWebcheckin").click();
		chrome.extension.sendRequest({
			"fieldId": "PaymentInputPaymentView_ACCTNO"
		}, function(response) {

			if (response.fieldValue !== undefined && response.fieldValue !== '') {
				var lastFourNumbers = response.fieldValue;
				if (lastFourNumbers.length >= 4) {
					lastFourNumbers = lastFourNumbers.substring(lastFourNumbers.length - 4);
					$("#BookingRetrieveSecurity_CARDNUMBER1").val(lastFourNumbers);
					highlightElement("#BookingRetrieveSecurity_CARDNUMBER1");
				}
			} else {
				console.log("Field PaymentInputPaymentView_ACCTNO is not defined in localStorage");
			}
		});

	});
	// ************************************
	// Web checkin PAGE 2
	// ************************************
	runIfExists("#CHECKINAVAILABLE", function() {
		console.log("Web Checkin page 2");
		chrome.extension.sendRequest({
			"fieldId": "autoAcceptTaC"
		}, function(response) {
			if (response.fieldValue !== "off") {
				$("input[type='checkbox']").click();
				$("#SecurityQuestionTerms_ButtonSubmit").click();
			}
		});

	});

	// ************************************
	// Web checkin PAGE 3
	// ************************************
	runIfExists("#paxDOC_1  #paxDocOptIn_0", function() {
		console.log("Web Checkin page 3");
		setValueToField("dobDay_ADT0");
		setValueToField("dobMonth_ADT0");
		setValueToField("dobYear_ADT0");
		setValueToField("nationality_ADT0");
		setValueToField("document_ADT0");
		setValueToField("PaxInputSegments$docNumber_ADT0");
		setValueToField("PaxInputSegments$docCountry_ADT0");
		setValueToField("docExpiryDay_ADT0");
		setValueToField("docExpiryMonth_ADT0");
		setValueToField("docExpiryYear_ADT0");
		$("#paxDocOptIn_0").click();
	});

	// ************************************
	// Web checkin seats selection
	// ************************************
	runIfExists("input#SeatMapInput_ButtonSubmit", function() {
		console.log("Seat seleciton");
		chrome.extension.sendRequest({
			"fieldId": "skipServicesChange"
		}, function(response) {
			if (response.fieldValue !== "off") {
				$("input[name='SeatMapInput$ButtonSkip']").click();
			}
		});
	});

	// ************************************
	// Web checkin add additional bags etc. https://www.bookryanair.com/SkySales/Booking.aspx?culture=en-ie&lc=en-ie#ExtraServicesChangeWCI
	// ************************************
	runIfExists("div#main input#sportsChangeValidation", function() {
		console.log("Extra bag and insurance");
		chrome.extension.sendRequest({
			"fieldId": "skipServicesChange"
		}, function(response) {
			if (response.fieldValue !== "off") {
				$("GrpServicesChange_GrpServicesChangeSamsoniteInputGroup_SamsoniteInputGrpServicesChangeSamInp_rbNoBagType").click();
				$("input[name='GrpServicesChange$ButtonSkip']").click();
				$("input[name='SeatMapInput$ButtonSkip']").click();
			}
		});
	});

}


// ************************************
// Helper functions
// ************************************

function injectScript(source) {
	var elem = document.createElement("script");
	elem.type = "text/javascript";
	elem.innerHTML = source;
	return document.head.appendChild(elem);
}

function setValueToField(fieldId) {

	chrome.extension.sendRequest({
		"fieldId": fieldId
	}, function(response) {
		if (response.fieldValue !== undefined && response.fieldValue !== '') {
			var selector = '#' + fieldId;
			var field = $(selector);
			if (field.length === 0) {
				selector = '*[name="' + fieldId + '"]';
				console.log("Setting value by field NAME", fieldId, selector);
				field = $(selector);
			} else {
				console.log("Setting value by field ID", fieldId);
			}
			$(field).val(response.fieldValue);
			highlightElement(selector);
		} else {
			console.log("Field " + fieldId + " is not defined in localStorage");
		}
	});

}

function executeIfConfigured(fieldId, expectedFieldValue, functionToBeExecuted) {
	chrome.extension.sendRequest({
		"fieldId": fieldId
	}, function(response) {
		if (response.fieldValue === expectedFieldValue) {
			functionToBeExecuted();
		}
	});
}

function clickOnElement(id) {
	if ($(id)) {
		$(id).click();
		highlightElement(id);
	}
}

function highlightElement(id) {
	chrome.extension.sendRequest({
		"fieldId": "highlightChanges"
	}, function(response) {
		if (response.fieldValue === "off") {
			highlightChanges = "off";
		}
		if (highlightChanges === "on") {
			$(id).css("background", "orange").css("color", "black").css("border", "1px black solid");
		}
	});
}

function isURL(url) {
	return window.location.href.toLowerCase().indexOf(url.toLowerCase()) === 0;
}

function runIfDisapear(selector, callback) {
	if ($(selector).length === 0) {
		callback();
		return;
	} else {
		setTimeout("runIfDisapear('" + selector + "', " + callback + ")", 100);
	}
}


function runIfExists(selector, callback) {
	if ($(selector).length !== 0) {
		//console.log("runIfExists FOUND for " + selector);
		callback();
		return;
	} else {
		//console.log("runIfExists SET for " + selector);
		setTimeout("runIfExists(\"" + selector + "\", " + callback + ")", 1000);
	}
}
